package com.loma.xui;

import android.databinding.DataBindingUtil;
import android.databinding.ViewDataBinding;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import java.util.List;

/**
 * Created by ma on 2015/7/10.
 * RecyclerView通用数据绑定
 */
public class MyAdapter<T> extends RecyclerView.Adapter<MyAdapter.BindingHolder> {

    public List<T> mDatas;
    public final int layoutId;
    public final int br;


    /**
     * @param list 数据
     *  @param br BR.XXX
     *  @param layoutId 布局
     */
    public  MyAdapter(List<T> list, int br,int layoutId) {
        this.mDatas = list;
        this.layoutId = layoutId;
        this.br = br;
    }

    public static class BindingHolder extends RecyclerView.ViewHolder {
        private ViewDataBinding binding;

        public BindingHolder(View itemView) {
            super(itemView);
        }

        public ViewDataBinding getBinding() {
            return binding;
        }

        public void setBinding(ViewDataBinding binding) {
            this.binding = binding;
        }
    }

    @Override
    public BindingHolder onCreateViewHolder(ViewGroup viewGroup, int i) {
        ViewDataBinding binding = DataBindingUtil.inflate(LayoutInflater.from(viewGroup.getContext()),
                layoutId,
                viewGroup,
                false);

        BindingHolder holder = new BindingHolder(binding.getRoot());
        holder.setBinding(binding);

        return holder;
    }

    @Override
    public void onBindViewHolder(BindingHolder holder, int position) {

        holder.getBinding().setVariable(br, mDatas.get(position));
        holder.getBinding().executePendingBindings();
    }

    @Override
    public int getItemCount() {
        return mDatas.size();
    }
}
